package xyz.pascall.rabbitmq.consumer;

import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;
import xyz.pascall.rabbitmq.pojo.Order;

import java.io.IOException;
import java.util.Map;

@Component
public class OrderReceiver {

    private final Logger LOG = LoggerFactory.getLogger(getClass());

    /**
     * 接收消息(需要rabbitmq监听和处理)(监听：监听队列、监听交换机、监听routingKey)
     * @param order
     * @param channel
     * @param headers
     * @throws IOException
     */
    @RabbitListener(bindings = @QueueBinding(
            value=@Queue(value = "order-queue", durable = "true"),
            exchange = @Exchange(name = "order-exchange", durable = "true", type = "topic"),
            key = "order.#"
        )
    )
    @RabbitHandler
    public void onMessage(@Payload Order order,
                          Channel channel,
                          @Headers Map<String, Object> headers) throws IOException {

        LOG.info("订单编号为："+ order.getId());
        LOG.info("订单名称为："+ order.getName());
        LOG.info("订单消息编号为："+ order.getMessageId());

        Long deliveryTag = (Long) headers.get(AmqpHeaders.DELIVERY_TAG);

        // ACK 手动签收时，需要手动响应RabbitMQ服务器（已经接收到这个消息）
        // 在生产时，一般使用手动签收，不使用自动签收    manual：手动 auto：自动
        // spring.rabbitmq.listener.simple.acknowledge-mode=manual #手动签收
        channel.basicAck(deliveryTag, false);
    }
}
